<template>
  <je-modal
    v-model:visible="visible"
    title="选择功能"
    width="1250"
    :resize="false"
    maximizable
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <div class="function-container" style="height: 100%">
      <je-panel v-bind="options">
        <template #tbar>
          <!-- 头部内容 -->
          <div class="header">
            <!-- 产品 -->
            <je-dropdown :trigger="['click']">
              <je-button class="product-class" type="text">
                <i class="fal fa-align-justify" /><span>{{
                  productValue.PRODUCT_NAME
                }}</span></je-button
              >
              <template #overlay>
                <je-menu>
                  <je-menu-item
                    v-for="item in productData"
                    :key="item"
                    @click.stop="handleProductClick(item)"
                  >
                    {{ item.PRODUCT_NAME }}
                  </je-menu-item>
                </je-menu>
              </template>
            </je-dropdown>
            <je-button class="clean-right-border" type="text" @click="cleanCache">
              <i class="jeicon jeicon-broom"></i>清空缓存
            </je-button>
            <je-button class="clean-right-border" type="text" @click="xTreeTable.clearTreeExpand()"
              ><i class="fal fa-layer-group"></i>全部收起</je-button
            >
            <je-input-search
              v-model:value="searchValue"
              placeholder="搜索"
              label-field="text"
              sub-label-field="FUNCINFO_FUNCCODE"
              style="width: 280px; margin-left: 4px; top: -5px"
              allow-clear
              enter-button="搜索"
              @search="onSearch"
              @select="onSelect"
            >
              <template #prefix> <i class="fal fa-search" /> </template>
            </je-input-search>
          </div>
        </template>
        <template #default>
          <je-table
            ref="xTreeTable"
            resizable
            border="outer"
            :auto-resize="true"
            header-align="left"
            align="left"
            :draggable="false"
            row-id="id"
            row-key
            height="100%"
            :loading="loadingStatus"
            show-overflow="ellipsis"
            :data="tableData"
            :tree-config="{
              trigger: 'cell-dblclick',
              rowField: 'id',
              parentField: 'parent',
            }"
            size="mini"
            @cell-dblclick="dbRows"
            @current-change="onClickRow"
          >
            <je-table-column title="名称" field="text" tree-node width="300">
              <template #nodeIcon="{ row }">
                <i
                  :class="row.iconclass"
                  style="margin-right: 5px; cursor: pointer"
                  :style="`color: ${row.iconColor}`"
                />
              </template>
              <template #default="{ row }">
                {{ row.text }}
              </template>
            </je-table-column>
            <je-table-column title="编码" field="code" width="260"></je-table-column>
            <je-table-column title="类型" field="nodeInfoType" width="140">
              <template #default="{ row }">
                {{ formateCodeToText(row.nodeInfoType) }}
              </template>
            </je-table-column>
            <je-table-column title="创建人" field="SY_CREATEUSERNAME" width="100"></je-table-column>
            <je-table-column title="创建时间" field="SY_CREATETIME" width="140"></je-table-column>
            <je-table-column title="修改人" field="SY_MODIFYUSERNAME" width="100"></je-table-column>
            <je-table-column title="修改时间" field="SY_MODIFYTIME"></je-table-column>
          </je-table>
        </template>
      </je-panel>
    </div>
  </je-modal>
</template>

<script>
  import { onMounted, ref, toRefs, defineComponent, reactive, onBeforeMount, watch } from 'vue';

  import { Modal, Grid, Search, Panel, Button } from '@jecloud/ui';

  import { Dropdown, Menu } from 'ant-design-vue';

  import { GetFunctionTreeData, getProductData } from './../../api/index';

  import { pinyin, getCurrentUser } from '@jecloud/utils';
  const ADD_FUNCTION_TYPE = [
    {
      value: 'SYSTEM',
      label: '子系统',
      disabled: false,
      compontent: 'ModalSystem',
      icon: 'jeicon jeicon-subsystem',
      color: '#3265F5',
    },
    {
      value: 'MODEL',
      label: '模块',
      disabled: false,
      compontent: 'AddModal',
      icon: 'jeicon jeicon-function-module',
      color: '#B8741A',
    },
    {
      value: 'FUNC',
      label: '功能',
      disabled: false,
      compontent: 'ModalAdd',
      icon: 'jeicon jeicon-function',
      color: '#606266',
    },
    {
      value: 'FUNCFIELD',
      label: '集合',
      disabled: false,
      compontent: 'ModalAdd',
      icon: 'jeicon jeicon-subfunction',
      color: '#606266',
    },
  ];
  export default defineComponent({
    name: 'Function',
    components: {
      JeModal: Modal,
      JeButton: Button,
      JeDropdown: Dropdown,
      JeInputSearch: Search,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JePanel: Panel,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      const tableData = ref([]);
      // 从localStorage中获取用户唯一标识
      const { deptmentUserId } = getCurrentUser();

      const state = reactive({
        visible: props.visble,
        productData: [],
        productValue: {},
        searchValue: '',
        newArr: [],
        xTreeTable: '',
        loadingStatus: true,
        options: reactive({
          tbar: { size: 45 },
        }),
        checkedRow: {},
        storageProductId: ref(localStorage.getItem(deptmentUserId) || ''),
      });
      watch(
        () => state.productValue,
        (newVal) => {
          window.productParams = newVal;
        },
        { deep: true },
      );
      const methods = {
        formateCodeToText(code) {
          if (!code) return '';
          const item = ADD_FUNCTION_TYPE.find((item) => item.value === code);
          return (item && item.label) || '';
        },
        // 递归处理function 列表数据
        formatArrTable(arr) {
          arr.map((item) => {
            const obj = {};
            obj.FUNCINFO_FUNCCODE = item.FUNCINFO_FUNCCODE;
            obj.text = item.FUNCINFO_FUNCNAME;
            obj.id = item.JE_CORE_FUNCINFO_ID;
            state.newArr.push(obj);
            //递归循环
            item.children.length && methods.formatArrTable(item.children);
          });
          return state.newArr;
        },
        filterText(item, keyword) {
          // 目前匹配是编码和名称
          const text = item.text?.toLocaleLowerCase() ?? '';
          const code = item.FUNCINFO_FUNCCODE?.toLocaleLowerCase() ?? '';
          const pinyinText = pinyin(text, 'pinyin');
          const pinyinCode = pinyin(code, 'pinyin');
          if (
            text.includes(keyword) ||
            pinyinText.includes(keyword) ||
            pinyinCode.includes(keyword)
          ) {
            return true;
          }
          return false;
        },
        // 点击搜索之后的item
        onSelect(val, option) {
          state.searchValue = val;
          const row = state.xTreeTable.getRowById(option.id);
          if (!row) return false;
          state.checkedRow = { ...row };
          state.xTreeTable.setTreeExpand4Path({ row, expand: true }).then((row) => {
            state.xTreeTable.setSelectRow(row);
            state.xTreeTable.scrollToRow(row);
          });
        },
        // 搜索逻辑处理
        onSearch(keyword, resolve) {
          !keyword && state.xTreeTable.clearTreeExpand();
          const items = [];
          keyword = keyword.toLocaleLowerCase();
          state.newArr.forEach((item) => {
            if (methods.filterText(item, keyword)) {
              items.push(item);
            }
          });
          resolve(items);
        },
        // 点击列表record
        onClickRow({ row, newValue }) {
          if (!newValue) {
            return false;
          }
          state.checkedRow = row;
        },
        // 获取子系统table数据
        getTableData() {
          state.newArr = [];
          const params = {
            searchValue: state.searchValue.trim(),
            SY_PRODUCT_ID: state.productValue.JE_PRODUCT_MANAGE_ID,
          };
          GetFunctionTreeData(params)
            .then((res) => {
              tableData.value = methods.recursiveFilter(res.children);
              state.newArr = methods.formatArrTable(res.children) || [];
              state.loadingStatus = false; // 等加载到数据的时候loading就变为false
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
              console.log('error', err);
            });
        },
        // 递归处理function 列表数据
        recursiveFilter(arr) {
          arr.map((item) => {
            item.SY_CREATETIME = methods.formatTime(item.SY_CREATETIME);
            item.SY_MODIFYTIME = methods.formatTime(item.SY_MODIFYTIME);
            if (item.children) {
              //递归循环
              methods.recursiveFilter(item.children);
            }
            item.iconclass = methods.changeColor(item.nodeInfoType, 'icon');
            item.iconColor = methods.changeColor(item.nodeInfoType, 'color');
          });
          return arr;
        },
        changeColor(type, key) {
          const item = ADD_FUNCTION_TYPE.find((item) => item.value === type);
          return (item && item[key]) || '';
        },
        formatTime(time) {
          return time && time.substring(0, 10);
        },
        dbRows({ row }) {
          if (row.FUNCINFO_NODEINFOTYPE == 'FUNC') {
            state.checkedRow = row;
            methods.handleOk();
          }
        },
        handleOk() {
          if (['SYSTEM', 'MODEL'].includes(state.checkedRow.FUNCINFO_NODEINFOTYPE)) {
            Modal.alert('请选择功能！', 'info');
            return false;
          }
          const { FUNCINFO_FUNCCODE, FUNCINFO_FUNCNAME } = state.checkedRow;
          const { PRODUCT_CODE, PRODUCT_NAME, JE_PRODUCT_MANAGE_ID } = state.productValue;
          emit('changeModal', {
            FUNCINFO_FUNCNAME,
            FUNCINFO_FUNCCODE,
            PRODUCT_CODE,
            PRODUCT_NAME,
            JE_PRODUCT_MANAGE_ID,
          });
        },
        handleClose() {
          emit('changeModal', {});
        },
        // 获取产品数据
        getProduce() {
          const params = {
            tableCode: 'JE_PRODUCT_MANAGE',
            funcCode: 'JE_PLATFORM_PRODUCT_MANAGE',
            j_query: JSON.stringify({
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
          };
          getProductData(params)
            .then((res) => {
              state.productData = res;
              const checkId = state.storageProductId || res[0].JE_PRODUCT_MANAGE_ID;
              state.productValue =
                res.find((item) => checkId == item.JE_PRODUCT_MANAGE_ID) || res[0];
              state.storageProductId = checkId;
              localStorage.setItem(deptmentUserId, checkId);
              methods.getTableData();
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
              console.log('error', err);
            });
        },
        // 切换产品
        handleProductClick(item) {
          state.productValue = item;
          state.storageProductId = item.JE_PRODUCT_MANAGE_ID;
          localStorage.setItem(deptmentUserId, item.JE_PRODUCT_MANAGE_ID);
          state.searchValue = '';
          methods.getTableData();
        },
      };
      onBeforeMount(() => {
        methods.getProduce();
      });
      onMounted(() => {
        state.searchValue = '';
      });
      return {
        ...toRefs(state),
        ...methods,
        tableData,
      };
    },
  });
</script>
<style lang="less" scoped></style>
